<?php

namespace app\ship\command;

use app\ship\service\XhsService;
use think\admin\Command;
use think\console\Input;
use think\console\Output;
/**
 * 小红书同步订单
 * Class SmsNum
 * @package app\common\command
 */
class XhsSyncingOrders extends Command
{
    /**
     * 配置指令
     */
    protected function configure()
    {
        $this->setName('xship:xhsSyncingOrders');
        $this->setDescription('XhsSyncingOrders');
    }

    protected function execute(Input $input, Output $output)
    {
        $data = $this->queue->data;
        $shop_id = $data['shop_id'];
        $appid = $this->app->db->name("nice_shops")->where(['id'=>$shop_id])->value("authorizer_appid");
        $res = XhsService::instance(['appid'=>$appid])->getOrderList();
        if(!isset($res['data']) || !isset($res['data']['orderList']) ){
            $this->setQueueSuccess("未获取到订单信息");
        }
        $page = 1;
        $page_size = $res['data']['pageSize'];
        $total = $res['data']['total'];
        $max_page= $res['data']['maxPageNo'];
        if($total==0){
            $this->setQueueSuccess("暂无需要同步的订单");
        }
        $count = 0;
        $this->queue->message($total, $count, "正在同步24小时内的订单");
        $this->queue->message($total, $count, "总共需要同步{$total}个订单");
        $this->queue->message($total, $count, "正在同步第{$page}页");
        for ($page;$page<=$max_page;$page++){
            if($page==1){
                $list = $res['data']['orderList'];
            }else{
                $list = XhsService::instance(['appid'=>$appid])->getOrderList($page)['data']['orderList'];
            }
            foreach ($list as $v){
                $this->queue->message($total, $count, "正在同步订单【{$v['orderId']}】");
                $save_order_id = $this->app->db->name("nice_orders")->where(['order_no'=>$v['orderId'],'shop_id' => $shop_id])->value('id');
                if(!$save_order_id){
                    $save_order_id = $this->app->db->name("nice_orders")->insertGetId([
                        'order_no'=>$v['orderId'],
                        'shop_id' => $shop_id
                    ]);
                }
                XhsService::instance(['appid'=>$appid])->saveOrder($v['orderId'],$save_order_id);
                $this->queue->message($total, ++$count, "订单【{$v['orderId']}】同步完成");
            }

        }

        $this->setQueueSuccess("任务处理完成");
    }
}